<template>
  <div>
    <div style="position: fixed; right: 20px;bottom: 10px;">
      <img
        @click="openkf()"
        style="width: 80px; height: 80px;z-index: 1000000;"
        src="../assets/roobit.gif"
      ></img>
    </div>
    <div
      style="
        width: 300px;
        position: fixed;
        right: 200px;
        background-color: rgb(239, 245, 245);
        top: 200px;
        z-index: 99999;
        border-radius: 5px;
        box-shadow: 0 0 10px #938f8f, 0 0 3px #ffffff;
      "
      v-if="disable"
    >
      <div
        style="
          width: 100%;
          height: 50px;
          background-color: rgb(255, 255, 255);
          border-top-left-radius: 5px;
          border-top-right-radius: 5px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <div>
          <el-image
            style="width: 50px; height: 50px; margin-left: 5px; margin-top: 5px"
            src="https://i02piccdn.sogoucdn.com/aa5679f00fc09ae6"
            >hi</el-image
          >
        </div>
        <div
          ref="hi"
          class="hi"
          style="margin-left: -45px; font-size: 12px"
        ></div>
        <div>
          <i
            class="el-icon-service"
            style="margin-right: 12px; font-size: 20px"
            @click="rengong"
          ></i>
          <i
            @click="closekf()"
            class="el-icon-close"
            style="margin-right: 12px; font-size: 21px"
          ></i>
        </div>
      </div>
      <div
        style="text-align: center; font-size: 12px; color: #c7b8b8"
        v-if="able"
      >
        {{ kefumsg }}
      </div>
      <div style="height: 380px; overflow: auto; font-size: 12px">
        <div class="chat-container" v-for="item in msgs" :key="item.idd">
          <div
            class="message self"
            style="display: flex"
            v-if="item.type === '1'"
          >
            <p>{{ item.msg }}</p>
            <el-image
              style="
                width: 30px;
                height: 30px;
                margin-left: 15px;
                margin-top: 6px;
              "
              :src="avatar"
              >hi</el-image
            >
          </div>
          <div
            class="message other"
            style="display: flex"
            v-if="item.type === '2'"
          >
            <el-image
              style="
                width: 30px;
                height: 30px;
                margin-right: 15px;
                margin-top: 6px;
              "
              :src="avatar"
              >hi</el-image
            >
            <p v-html="item.msg" style="word-wrap: break-word"></p>
          </div>
          <!-- 更多消息... -->
        </div>
      </div>
      <div
        style="
          height: 80px;
          background-color: rgb(255, 255, 255);
          border-bottom-left-radius: 5px;
          border-bottom-right-radius: 5px;
        "
      >
        <input
          type="text"
          style="
            border: none;
            border: solid 0px;
            outline: none;
            height: 40px;
            width: 98%;
          "
          placeholder="请输入内容"
        />
        <el-button
          type="primary"
          size="small"
          style="margin-left: 80%"
          @click="sent()"
          >发送</el-button
        >
      </div>
    </div>
  </div>

  <!-- <div>
        <input placeholder="请输入">
        <button @click="sent()">发送</button>
        <button @click="rengong">转人工</button>
        <div></div>
    </div> -->
</template>
<script>
import Cookies from "js-cookie";
export default {
  name: "Chat",
  data() {
    return {
      disable: false,
      able: false,
      avatar:
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2F0fbd54b2-0c56-4870-b041-aa37e6fc4491%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1711872216&t=74c3f5d18785ad9f83275c405ecbc86f",
      websocket: "",
      msg: "",
      msgs: [],
      kefu: "请稍等，为您转接人工客服~",
      text: "我是小煋,很高兴为您服务",
      obj: {
        id: "",
        msg: "",
        type: "1",
        to: "222222",
        nowTime: "",
      },
      kefumsg: "客服正在赶来",
      intervalId: "",
      kefuobj: {},
      time:0
    };
  },
  created() {
    this.getKefu();

    this.renmen();
  },
  methods: {
    closekf() {
      this.disable = false;
      this.websocket.close
    },
    openkf() {
     var that=this;
      if (this.time === 0) {
        this.time = 5;
        var index=setInterval(function () {
          that.time=that.time-1;
          if (that.time === 0) {
            clearInterval(index)
          }
        }, 1000);
        this.disable=true
        this.hello()
      }else{
        this.$message.error(that.time+"后触发")
      }
    },
    getKefu() {
      this.$http.get("/kefu/getKefu").then((res) => {
        this.kefuobj = res.data;
        console.log(this.kefuobj);
        this.listenMsg();
      });
    },

    getke() {
      console.log("kefuobj",this.kefuobj)
      if (this.kefuobj === ""||this.kefuobj===null||this.kefuobj===undefined) {
        this.kefumsg = "客服休息中";
        return;
      }
      this.obj.to = this.kefuobj.id;
      this.kefumsg = "客服" + this.kefuobj.name + "为您服务";
      clearInterval(this.intervalId);
    },
    rengong() {
      this.able = true;
      var that = this;
      this.intervalId = setTimeout(function () {
        that.getke();
      }, 2000);
      // this.websocket = new WebSocket(
      //     "ws://39.98.162.10:8000/websocket/111111"
      // )
    },
    insertMsg(item) {
      this.$http.post("/kefu/insertMsg", item).then((res) => {});
    },
    listenMsg() {
      if (Cookies.get("userId") === undefined) {
        var id = Math.floor(Math.random() * 999999);
        Cookies.set("userId", id);
      } else {
        this.obj.id = Cookies.get("userId");
      }
      var that = this;
      console.log(1, this.kefuobj);
      this.websocket = new WebSocket(
        "ws://39.98.162.10:8001/websocket/" + that.obj.id + "/" + that.kefuobj.id
      );

      this.websocket.addEventListener("message", function (e) {
        var data = JSON.parse(e.data);
        that.msgs.push(data);
      });
    },
    sent() {
      var input = document.querySelector("input").value;
      var a = this.obj;
      a.msg = input;
      // this.msgs.push(a);
      this.msgs.push(JSON.parse(JSON.stringify(a)));
      this.insertMsg(a);

      // window.scrollTo(0, document.body.scrollHeight);
      document.querySelector("input").value = "";
      if (this.able) {
        this.websocket.send(JSON.stringify(this.obj));
      } else {
        this.$http.get("/kefu/question?question=" + input).then((res) => {
          this.msgs.push(res.data);
          if (res.data.msg === this.kefu) {
            this.rengong();
          }
        });
      }
    },
    renmen() {
      var a = {};
      a.id = this.obj.to;
      a.to = this.obj.id;
      (a.msg =
        "您好,有什么需要帮助的？<br> 中药图谱是什么？ <br> 煋月博客最新内容？ <br> 煋玥阁的功能有哪些？ <br>投诉与建议"),
        (a.type = "2");

      this.msgs.unshift(a);
      // this.insertMsg(a)
    },
    hello() {
      var text = this.text; // 要显示的文本
      var delay = 100; // 每个字之间的延迟时间（毫秒）
      var div = document.getElementsByClassName("hi");

      var index = 0; // 当前要显示的字符的索引
      var that = this;
      var intervalId = setInterval(function () {
        if (index < text.length&&that.$route.name==="home"&&that.disable===true) {
          that.$refs.hi.innerHTML += text.charAt(index); // 将当前字符添加到文本容器中
          index++; // 更新索引以显示下一个字符
        } else {
          clearInterval(intervalId); // 所有字符都已显示，清除定时器
        }
      }, delay);
    },
  },
};
</script>
<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;

  margin: 0 auto;
}

.message {
  margin-bottom: 10px;
  padding: 0px;
  border-radius: 10px;
  max-width: 80%;
  padding-left: 10px;
}

.message.self {
  /* background-color: #e0f7fa; */
  align-self: flex-end;
  text-align: right;
}

.message.other {
  /* background-color: #f9f9f9; */
  align-self: flex-start;
  text-align: left;
}
</style>